﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using Common.ORM.Repository;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;

namespace Common.ORM.Extensions
{
    public static class AddORMExtension
    {
        /// <summary>
        /// 注入ORM上下文
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        public static void AddORM(this IServiceCollection services,IConfiguration configuration)
        {
            var connectionString = configuration["ConnectionStrings:pgsql"];
            SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig
            {
                DbType = DbType.PostgreSQL,
                ConnectionString = connectionString,
                IsAutoCloseConnection = true,
                ConfigureExternalServices = new ConfigureExternalServices()
                {
                    EntityService = (c,p)=>
                    {

                        if (c.PropertyType.IsGenericType && c.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                        {
                            p.IsNullable = true;
                        }

                        // if (c.PropertyType == typeof(string) && c.GetCustomAttribute<RequiredAttribute>() == null && p.IsNullable == false)
                        // {
                        //     //string类型如果没有Required isnullable=true
                        //     p.IsNullable = true;
                        // }
                    }
                }
            }, db =>
            {
                
                //单例参数配置，所有上下文生效
                // db.Aop.OnLogExecuting = (sql, pars) =>
                // {
                //     Console.WriteLine(sql);//输出sql
                //     var par = string.Empty;
                //     foreach (var item in pars)
                //     {
                //         par += item.ParameterName + "=" + item.Value?.ToString() +"\n";
                //     }
                //     Console.WriteLine(par);
                // };

                //技巧：拿到非ORM注入对象
                //services.GetService<注入对象>();
            });


            services.AddSingleton<ISqlSugarClient>(sqlSugar);

        }
    }
}
